import { SafeTimer } from './safeTimers'

// 网络诊断工具
export interface NetworkDiagnosticResult {
  isOnline: boolean
  canReachGoogle: boolean
  canReachSpeechService: boolean
  userAgent: string
  timestamp: string
}

export class NetworkDiagnostic {
  static async runDiagnostic(): Promise<NetworkDiagnosticResult> {
    const result: NetworkDiagnosticResult = {
      isOnline: typeof navigator !== 'undefined' && navigator.onLine !== undefined ? navigator.onLine : true,
      canReachGoogle: false,
      canReachSpeechService: false,
      userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : 'Unknown',
      timestamp: new Date().toISOString()
    }

    // 测试Google连接（带超时）
    try {
      const controller = new AbortController()
      const timeoutId = SafeTimer.setTimeout(() => {
        controller.abort()
      }, 3000) // 3秒超时
      
      // 使用更可靠的测试端点
      await fetch('https://www.google.com/generate_204', {
        method: 'GET',
        mode: 'no-cors',
        cache: 'no-cache',
        signal: controller.signal
      })
      SafeTimer.clearTimeout(timeoutId)
      result.canReachGoogle = true
    } catch (error) {
      // 如果第一个测试失败，尝试备用测试
      try {
        const controller2 = new AbortController()
        const timeoutId2 = SafeTimer.setTimeout(() => {
          controller2.abort()
        }, 2000) // 2秒超时
        
        await fetch('https://www.google.com/favicon.ico', {
          method: 'HEAD',
          mode: 'no-cors',
          cache: 'no-cache',
          signal: controller2.signal
        })
        SafeTimer.clearTimeout(timeoutId2)
        result.canReachGoogle = true
      } catch (error2) {
        result.canReachGoogle = false
        console.log('Google连接测试失败:', error2)
      }
    }

    // 测试语音服务连接（使用多个测试端点）
    try {
      const controller = new AbortController()
      const timeoutId = SafeTimer.setTimeout(() => {
        controller.abort()
      }, 3000) // 3秒超时
      
      // 测试多个可能的语音服务端点
      const testUrls = [
        'https://www.google.com/generate_204',
        'https://www.google.com/favicon.ico',
        'https://www.bing.com/favicon.ico'
      ]
      
      let success = false
      for (const url of testUrls) {
        try {
          await fetch(url, {
            method: 'HEAD',
            mode: 'no-cors',
            cache: 'no-cache',
            signal: controller.signal
          })
          success = true
          break
        } catch (e) {
          continue
        }
      }
      
      SafeTimer.clearTimeout(timeoutId)
      result.canReachSpeechService = success
    } catch (error) {
      result.canReachSpeechService = false
      console.log('语音服务连接测试失败:', error)
    }

    return result
  }

  static getBrowserSupport(): { supported: boolean; browser: string; version?: string } {
    const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : 'Unknown'
    let browser = 'Unknown'
    let version = undefined
    let supported = false

    if (userAgent.includes('Chrome')) {
      browser = 'Chrome'
      const match = userAgent.match(/Chrome\/(\d+)/)
      version = match ? match[1] : undefined
      supported = true
    } else if (userAgent.includes('Safari') && !userAgent.includes('Chrome')) {
      browser = 'Safari'
      const match = userAgent.match(/Version\/(\d+)/)
      version = match ? match[1] : undefined
      supported = true
    } else if (userAgent.includes('Edge')) {
      browser = 'Edge'
      const match = userAgent.match(/Edge\/(\d+)/)
      version = match ? match[1] : undefined
      supported = true
    } else if (userAgent.includes('Firefox')) {
      browser = 'Firefox'
      const match = userAgent.match(/Firefox\/(\d+)/)
      version = match ? match[1] : undefined
      supported = false // Firefox对Web Speech API支持有限
    }

    return { supported, browser, version }
  }

  static getRecommendations(result: NetworkDiagnosticResult): string[] {
    const recommendations: string[] = []

    if (!result.isOnline) {
      recommendations.push('请检查网络连接')
    }

    if (!result.canReachGoogle) {
      recommendations.push('无法连接到Google服务，请检查网络或防火墙设置')
    }

    if (!result.canReachSpeechService) {
      recommendations.push('语音服务连接失败，可能需要配置代理或检查企业网络限制')
    }

    const browserSupport = this.getBrowserSupport()
    if (!browserSupport.supported) {
      recommendations.push(`当前浏览器(${browserSupport.browser})对语音识别支持有限，建议使用Chrome、Edge或Safari`)
    }

    if (recommendations.length === 0) {
      recommendations.push('网络连接正常，如果仍有问题，请尝试重启浏览器')
    }

    return recommendations
  }
}
